package com.cyz.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyz.dao.OrderDao;
import com.cyz.dao.ProductDao;
import com.cyz.entity.Order;
import com.cyz.entity.Product;
import com.cyz.service.ProductService;
import io.lettuce.core.RedisClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/consumer")
@Slf4j
public class ConsumerController {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ProductDao productDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/start")
    public synchronized String startConsumer() throws UnsupportedEncodingException {
        Product product = productDao.selectOne(new QueryWrapper<Product>().eq("product_name", "iPhone 14 Pro Max"));
        int oldTotal = product.getTotal();
        if (oldTotal > 0){
            Message receive = rabbitTemplate.receive("spring.queue");
            if (receive != null){
                byte[] body = receive.getBody();
                String s = new String(body, "utf-8");
                log.info(s);
            }
            product.setTotal(oldTotal - 1);
            productDao.update(product, new QueryWrapper<Product>().eq("product_name","iPhone 14 Pro Max"));
        }else {
            log.info("手速太慢了，没有抢到");
        }

        return "over";
    }

    @GetMapping("/secKill")
//    @Transactional
    public String redisStart() throws UnsupportedEncodingException {
        //将Key中的值递减
        Long stock = redisTemplate.opsForValue().decrement("remainingCount");

        if (stock >= 0){//如果还有库存，执行剩下的操作
            //创建订单

            //消费MQ
            Message receive = rabbitTemplate.receive("spring.queue");
            if (receive != null){
                byte[] body = receive.getBody();
                String s = new String(body, "utf-8");
                log.info(s);
            }
            //更新数据到数据库
        }else {
            log.info("手速太慢了，没有抢到...");
        }

        return "String.valueOf(stock)";
    }
}
